package com.ezlcp.form.web.file;

import com.ezlcp.commons.model.FileModel;
import com.ezlcp.commons.utils.FileUtil;
import com.ezlcp.form.service.FileServiceImpl;
import jakarta.activation.MimetypesFileTypeMap;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * @author Elwin ZHANG
 * @description: 本地文件系统存储操作 <br/>
 * @date 2022/5/16 10:32
 */
@Slf4j
@Component("file")
public class FileOperator extends BaseFileOperator {

    @Resource
    FileServiceImpl fileService;

    public String getTitle() {
        return "本地文件系统";
    }

    public String getType() {
        return "file";
    }

    public void downFile(HttpServletResponse response, com.ezlcp.form.entity.File sysFile, boolean isScale, boolean isDownload) {
        try {
            // 创建file对象
            String fileName = sysFile.getFileName().toLowerCase();
            String path = SysFileUtil.getFilePath(sysFile, isScale);
            File file = new File(path);
            String ext = new MimetypesFileTypeMap().getContentType(file);
            response.setContentType(ext);
            addHeader(fileName, response, isDownload);
            FileUtil.downLoad(file, response);
        } catch (Exception e) {
            log.error("------FileOperator.downFile is error :" + e.getMessage());
        }
    }

    public int delFile(String path) {
        String fullPath = SysFileUtil.getUploadPath() + path;
        File file = new File(fullPath);
        file.delete();
        return 0;
    }

    public FileModel createFile(String fileName, byte[] bytes) {
        String extName = FileUtil.getFileExt(fileName);
        String relFilePath = getRealPath();
        String fullPath = SysFileUtil.getUploadPath() + relFilePath;
        File dirFile = new File(fullPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        relFilePath += File.separator + fileName;
        String filePath = fullPath + File.separator + fileName;
        try {
            FileUtil.writeByte(filePath, bytes);
        } catch (Exception e) {
            log.error("------FileOperator.createFile is error :" + e.getMessage());
        }

        FileModel model = new FileModel();
        model.setFileName(fileName);
        model.setExtName(extName);
        model.setRelPath(relFilePath);
        return model;
    }
}